﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
using System.IO;

namespace Web.Account
{
    public partial class Register : System.Web.UI.Page
    {
        static string prevPage = String.Empty;
        static string defaultImage = "~/UserImages/noavatar.png";
        static USER user;
        static long UserID;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            if (Request.UrlReferrer != null)
                prevPage = Request.UrlReferrer.ToString();

            user = (USER)Session["User"];
            if (user != null)
            {
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if (((bool)user.IS_ADMIN) || ((bool)r.IS_MANAGER))
                {
                    LoadRole();
                    if (!(bool)user.IS_SUPER_USER)
                    {
                        divIsSuperUser.Visible = false;
                        divIsAdmin.Visible = false;
                    }
                }
                else
                {
                    Response.Redirect("../Home.aspx");
                }
            }
        }
        private void LoadRole()
        {
            ddlRole.DataSource = RoleService.GetRoles();
            ddlRole.DataBind();
            ddlRole.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
      
        private int RegisterNewUser()
        {
            USER user = new USER();
            user.DELETED = false;
            user.CREATED_BY = 1;
            user.DATE_ENTERED = DateTime.Now;
            user.MODIFIED_USER_ID = 1;
            user.DATE_MODIFIED = user.DATE_ENTERED;
            user.PWD_LAST_CHANGED = user.DATE_ENTERED;
            //User login & role
            user.USER_NAME = txtUsername.Text;
            user.PRIMARY_EMAIL = txtPrimaryMail.Text;
            user.SUR_NAME = txtFirstName.Text;
            user.NAME = txtLastName.Text;
            user.USER_HASH = RSAEncryption.PrivateEncryption(txtPassword.Text);
            user.IS_ADMIN = chbIsAdmin.Checked;
            user.ACTIVE = chbIsActive.Checked;
            user.IS_SUPER_USER = chbIsSuperUser.Checked;
            if (ddlRole.SelectedValue != "-1")
            {
                user.ROLE_ID = Convert.ToInt64(ddlRole.SelectedValue);
            }
            else
            {
                user.ROLE_ID = -1;
            }

            user.ACTIVE = true;
            
            
            //More information
            user.TITLE = txtTitle.Text;
            user.FAX = txtFax.Text;
            user.DEPARTMENT = txtDepartment.Text;
            user.OTHER_EMAIL = txtOtherEmail.Text;
            user.PHONE_OFFICE = txtOfficePhone.Text;

            user.PHONE_MOBILE = txtMobilePhone.Text;
            //user.REPORTS_TO_ID = 1;//check
            user.PHONE_HOME = txtHomePhone.Text;
            user.PHONE_SECONDARY = txtSecondaryPhone.Text;
            user.CRM_EXTENSION = txtCRMPhoneEx.Text;
            //User address
            user.ADDRESS_STREET = txtStreetAddress.Text;
            user.ADDRESS_COUNTRY = txtCountry.Text;
            user.ADDRESS_CITY = txtCity.Text;
            user.ADDRESS_POSTALCODE = txtPostalCode.Text;
            user.ADDRESS_STATE = txtState.Text;
            
            //Add new user
            string img = user.IMAGE;
            if (AsyncUpload1.UploadedFiles.Count > 0)
            {
                string filename = "~/ProductImages/" + DateTime.Now.ToString("ddMMyyhhmmssttfff") + AsyncUpload1.UploadedFiles[0].GetExtension();
                AsyncUpload1.UploadedFiles[0].SaveAs(Server.MapPath(filename));
                user.IMAGE = filename;
            }
            else
                user.IMAGE = defaultImage;
            return UserService.AddNewUser(user);
        }
        
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int checkUser = UserService.CheckExist(txtUsername.Text);
            if (checkUser == 0)
            {
                int regResult = RegisterNewUser();
                if (regResult == 1)
                {
                    RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Add new user successful !" + "','" + "Users.aspx" + "');");
                    //MessageBox.Show(this.Page, Page.GetType(), "Add new user successful !", "Users.aspx");
                }
                else
                    RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not add new user !" + "');");
                    //MessageBox.Show(this.Page, Page.GetType(), "Cannot add new user !", "");
                    
            }
            else if (checkUser == 1)
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Username already exists !" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Username already exists !", "");
        }

        protected void btn_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(prevPage);
        }
        protected void DeleteImage_Click(object sender, EventArgs e)
        {
            imgprw.Src = defaultImage;
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            //Bind the RadComboBod 
            //  FileUploadControl.PostedFile.InputStream.Dispose();
        }
    }
}